<?php


namespace PKApp\Poster;


use PKApp\Poster\Classes\ImageService;
use PKApp\Poster\Classes\PosterService;
use PKApp\Poster\Classes\TextService;
use PKApp\Site\Classes\SiteController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

class ApiGetPoster extends SiteController
{

    protected $service;
    // _id_site 是用户指定
    protected $id_poster, $_id_site;
    protected $result;

    public function __construct()
    {
        $this->service = new PosterService();
        $this->result = ['posterType' => ''];
    }

    public function Main()
    {
        $this->id_poster = Numbers::To(request()->get('id'));
        $this->_id_site = Numbers::To(request()->get('siteId'));
        $this->_id_site > 0 ?: $this->_id_site = $this->getSiteEntity()->Id;
        Numbers::IsId($this->id_poster) ?: $this->noticeByJson('posterIdEmpty');
        $cache_file = dict('cache_file') . $this->id_poster . '_' . $this->_id_site;
        $cache_dir = dict('cache_dir');
        $cache_params = cache()->Tmp()->ReadByJSON($cache_file, $cache_dir);
        empty($cache_params) ?: $this->json($cache_params);
        $this->getPoster();
        switch (Arrays::GetKey('posterType', $this->result, 'poster_TypeEmpty')) {
            case 'image':
                $this->getImg();
                break;
            case 'text':
                $this->getText();
                break;
            default:
                $this->noticeByJson('poster_TypeError');
                break;
        }
        cache()->Tmp()->WriteByJSON($cache_file, $this->result, $cache_dir);
        $this->json($this->result);
    }

    protected function getPoster()
    {
        $entity_poster = $this->service->interface_getEntityById($this->id_poster, ['posterType', 'name']);
        $this->result = array_merge($this->result, [
            'name' => $entity_poster['name'], 'posterType' => $entity_poster['posterType'],
        ]);
    }

    protected function getImg()
    {
        $service_img = new ImageService();
        $list_img = $service_img->GetList([
            'siteId' => $this->_id_site,
            'posterId' => $this->id_poster,
        ], ['image_src', 'image_url']);
        $this->result = array_merge($this->result, ['list' => $list_img]);
    }

    protected function getText()
    {
        $service_text = new TextService();
        $list_text = $service_text->GetList([
            'siteId' => $this->_id_site,
            'posterId' => $this->id_poster,
        ], ['text', 'fontColor', 'url']);
        $this->result = array_merge($this->result, ['list' => $list_text]);
    }

}